﻿var allowEx = [".jpg", ".png", ".bmp"];

var document = fl.createDocument(); 
document.library.selectAll();
document.library.deleteItem();
ergodicFolder(getPath(fl.scriptURI) + "preResource/");
document.exportSWF(getPath(fl.scriptURI) + "resource.swf");
document.close(false);
/**
 * 导入文件到库
 * 并生成包含此文件的元件
 * @document 文档引用
 * @filePath 导入的文件路径
 * @packageName 包名, 若无包名，则无需填写；如果有，则以"."结尾
 */
function importFile(document, filePath, packageName)
{
	document.importFile(filePath, false);
	var item = document.convertToSymbol("movie clip", "fsd@#$@%", "top left");			//使用临时名称，避免冲突
	var folder = packageName.split(".").join("/");
	if(folder != "" && document.library.findItemIndex(folder) == "")
	{
		document.library.newFolder(folder);
	}
	item.name = getFileNameWithoutExtension(filePath);
	item.linkageExportForAS = true;
	item.linkageExportInFirstFrame = true;
	item.linkageClassName = packageName + item.name;
	if(folder != "")
	{
		document.library.moveToFolder(folder.substring(0, folder.length - 1), item.name);
		document.library.moveToFolder(folder.substring(0, folder.length - 1), getFileName(filePath));
	}
	document.deleteSelection();
}

/**
 * 遍历文件夹
 * @path 文件夹路径，以"/"或者"\\"结尾
 * @packageName 包名，, 若无包名，则无需填写；如果有，则以"."结尾
 */
function ergodicFolder(path, packageName)
{
	if(!packageName)
		packageName = "";
	var files = FLfile.listFolder(path, "files");
	if(files != null)
	{
		for(var i = 0; i < files.length; i++)
		{
			var file = path + files[i];
			if(allowEx.indexOf(getExtension(files[i]).toLowerCase()) != -1)
			{
				importFile(document, file, packageName);
			}
		}
	}
	var folders = FLfile.listFolder(path, "directories");
	if(folders != null)
	{
		for(var i = 0; i < folders.length; i++)
		{
			ergodicFolder(path + folders[i] + "/", packageName + folders[i] + ".");
		}
	}
}
 /**
  * 获取去掉文件名的路径
  */
function getPath(path)
{
	var index = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
	return path.substring(0, index + 1);
}
/**
 * 获取文件名
 */
function getFileName(path)
{
	var index = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
	index += 1;
	return path.substring(index, path.length);
}

/**
 * 获取扩展名
 */
function getExtension(path)
{
	return path.substring(path.lastIndexOf("."), path.length);
}

/**
 * 获取不带扩展名的文件名
 */
function getFileNameWithoutExtension(path)
{
	var index = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
	index += 1;
	return path.substring(index, path.lastIndexOf("."));
}